<!DOCTYPE html>
<html lang="zh-cn">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
	<style>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}

		body {
			display: flex;
			justify-content: center;
			align-items: center;
			background-color: #aaa;
		}

		main {
			display: flex;
			flex-direction: column;
			width: 100vw;
			max-width: 600px;
			height: 100vh;
			background-color: #f2f2f2;
		}

		header {
			display: flex;
			align-items: center;
			padding: 0 10px;
			width: 100%;
			height: 90px;
			font-size: 20px;
			font-weight: 700;
			background-color: #fff;
		}

		.file-info {
			width: 100%;
			height: calc(100%);
			overflow-x: hidden;
			overflow-y: auto;
			padding: 10px;
		}

		.card {
			width: 100%;
			height: max-content;
			background-color: #fff;
			border-radius: 10px;
			border: 1px solid #eee;
			box-shadow: 0 2px 8px 4px #eee;
		}

		.info-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			height: 60px;
			padding: 0 20px;
			font-size: 18px;
		}

		.not-info {
			justify-content: center;
		}

		.download-button {
			width: 100%;
			height: max-content;
			padding: 0 10px;
		}

		.download-button div {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 60px;
			color: #fff;
			font-size: 18px;
			font-weight: 700;
			border-radius: 10px;
			background-color: #482dea;
			margin-bottom: 30px;
			box-shadow: 0 2px 8px 4px #ccc;
		}
	</style>
</head>
<body>
	<main>
		<header>
			<div>10.49.57.179:9091</div>
		</header>
		<div class="file-info">
			<div class="card">
				<div class="not-info info-item">获取文件信息中...</div>
			</div>
		</div>
		<div class="download-button" style="display: none;">
			<div>下载文件</div>
		</div>
	</main>
	<script>
		window.onload = () => {
			const title = document.querySelector("header div");
			title.innerHTML = window.location.host;
			RenderFilesInfo();
		};

		let download = false;
		function DownloadFile(event) {
			event.preventDefault();
			if(download) {
				alert("文件已在下载中!");
				return;
			}

			download = true;
			const message = document.querySelector(".download-button div");
			message.innerHTML = "文件下载中...";

			const ajax = new XMLHttpRequest();
			ajax.open("POST", "./download");
			ajax.send(JSON.stringify({
				uuid: localStorage.getItem("file_uuid")
			}));

			ajax.onreadystatechange = function() {
				if(ajax.readyState !== 4) {
					return;
				}

				if(ajax.status !== 200) {
					alert("文件下载失败");
					download = false;
					message.innerHTML = "下载文件";
					return;
				}
				const data = JSON.parse(ajax.response);
				if(!data.status) {
					alert("文件下载失败");
					download = false;
					message.innerHTML = "下载文件";
					return;
				};

				downloadFileFromBase64(`data:${data.mimetype};base64,${data.content}`, data.name, data.mimetype);
				download = false;
				message.innerHTML = "下载文件";
			};

			ajax.onerror = function(err) {
				download = false;
				message.innerHTML = "下载文件";
				console.log(err);
				alert("文件下载失败");
			};
		};

		function downloadFileFromBase64(base64Data, filename, contentType) {  
			const sliceSize = 1024;  
			const byteCharacters = atob(base64Data.split(",")[1]);  
			const byteArrays = [];  
		
			for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {  
				const slice = byteCharacters.slice(offset, offset + sliceSize);  
		
				const byteNumbers = new Array(slice.length);  
				for (let i = 0; i < slice.length; i++) {  
					byteNumbers[i] = slice.charCodeAt(i);  
				}  
		
				const byteArray = new Uint8Array(byteNumbers);  
				byteArrays.push(byteArray);  
			}  
		
			const blob = new Blob(byteArrays, { type: contentType });
			const url = URL.createObjectURL(blob);  
			const a = document.createElement("a");  
			a.href = url;  
			a.download = filename;  
			a.style.display = "none";  
			document.body.appendChild(a);  
			a.click();  
			URL.revokeObjectURL(url);
			document.body.removeChild(a);
		};

		function convertBytesToMBGB(bytes, decimalPlaces = 2) {
			if (bytes < 1024) {
				return `${bytes} B`;
			}

			if (bytes < 1024 * 1024) {
				return `${(bytes / 1024).toFixed(decimalPlaces)} KB`;
			}

			if (bytes < 1024 * 1024 * 1024) {
				return `${(bytes / (1024 * 1024)).toFixed(decimalPlaces)} MB`;
			}

			return `${(bytes / (1024 * 1024 * 1024)).toFixed(decimalPlaces)} GB`;
		};

		function RenderFilesInfo() {
			const card = document.querySelector(".card");
			const notInfoEle = document.querySelector(".not-info");
			const downloadButton = document.querySelector(".download-button");
			const ajax = new XMLHttpRequest();

			ajax.open("POST", "./file_info");
			ajax.send(JSON.stringify({
				uuid: localStorage.getItem("file_uuid")
			}));

			ajax.onreadystatechange = function() {
				if(ajax.readyState !== 4) {
					return;
				}

				if(ajax.status !== 200) {
					notInfoEle.innerHTML = "文件信息获取失败";
					return;
				}

				const data = JSON.parse(ajax.response);
				if(!data.status) {
					notInfoEle.innerHTML = "文件信息获取失败";
					return;
				}
				const file = data.file;
				card.innerHTML = `
					<div class="info-item">
						<span>名称：</span>
						<span class="info-name">${file.name.length > 18 ? `${file.name.slice(0, 15)}...` : file.name}</span>
					</div>
					<div class="info-item">
						<span>大小：</span>
						<span class="info-size">${convertBytesToMBGB(file.size)}</span>
					</div>
					<div class="info-item">
						<span>MIME类型：</span>
						<span class="info-mimetype">${file.mimetype}</span>
					</div>
					<div class="info-item">
						<span>类型：</span>
						<span class="info-type">共享文件</span>
					</div>
				`;
				downloadButton.setAttribute("style", "display: block;");
				downloadButton.addEventListener("touchend", DownloadFile);
				downloadButton.addEventListener("click", DownloadFile);
			};

			ajax.onerror = function (err) {
				console.log(err);
				notInfoEle.innerHTML = "文件信息获取失败";
			};
		}
	</script>
</body>
</html>